package com.maixun.lib_choosefile.ui.preview

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.maixun.lib_choosefile.LocalFileConst
import com.maixun.lib_choosefile.R
import com.maixun.lib_choosefile.entity.FileType
import kotlinx.android.synthetic.main.activity_preview.*

/**
 * @author：Lmoumou
 * @date：2020/10/20
 */
class PreviewActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_preview)
        initToolbar()

        intent.extras?.let {
            tvTitle.text = it.getString(LocalFileConst.FILE_NAME)
            when (it.getSerializable(LocalFileConst.FILE_TYPE2) as FileType) {
                FileType.VIDEO -> {
                    addFragment(R.id.flContent, PreviewVideoFragment.newInstance(it))
                }
                FileType.AUDIO -> {
                    addFragment(R.id.flContent, PreviewAudioFragment.newInstance(it))
                }
                FileType.IMAGE -> {
                    addFragment(R.id.flContent, PreviewImageFragment.newInstance(it))
                }
                FileType.DOCUMENT -> {
                    addFragment(R.id.flContent, PreviewDocumentFragment.newInstance(it))
                }
                FileType.OTHER -> {
                    addFragment(R.id.flContent, PreviewOtherFragment.newInstance(it))
                }
                FileType.DEFAULT -> {
                    addFragment(R.id.flContent, PreviewDefaultFragment.newInstance(it))
                }
            }
        }

    }

    private fun initToolbar() {
        mToolbar.apply {
            title = ""
            this@PreviewActivity.setSupportActionBar(this)
            this@PreviewActivity.supportActionBar?.apply {
                setHomeButtonEnabled(true)
                setDisplayHomeAsUpEnabled(true)
            }
            this.setNavigationOnClickListener {
                this@PreviewActivity.onBackPressed()
            }
        }
    }

    private var mFragment: Fragment? = null

    /**
     * 展示Fragment
     * */
    private fun addFragment(frameLayoutId: Int, fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        if (fragment.isAdded) {
            if (mFragment != null) {
                transaction.hide(mFragment!!).show(fragment)
            } else {
                transaction.show(fragment)
            }
        } else {
            if (mFragment != null) {
                transaction.hide(mFragment!!).add(frameLayoutId, fragment)
            } else {
                transaction.add(frameLayoutId, fragment)
            }
        }
        mFragment = fragment
        transaction.commit()
    }
}